package com.hz.winnie.demands.web.controller.user;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hz.winnie.demands.pojo.User;
import com.hz.winnie.demands.service.UserService;
import com.hz.winnie.demands.utils.MD5Util;

/**
 * @description 用户Controller
 * @author winnie
 * @date 2011-4-8
 * @version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 新建用户
     * 
     * @param product
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/add")
    public String add(@ModelAttribute User user, Model model) throws Exception {
	if (user == null || StringUtils.isBlank(user.getUserName())) {
	    return "/user/add";
	}
	if (!user.getPassword().equals(user.getPasswordrpt())) {
	    model.addAttribute("msg", "密码不同");
	    return "/user/add";
	}
	user.setPassword(MD5Util.md5(user.getPassword()));
	userService.addUser(user);
	return "user/success";
    }

    /**
     * 修改用户密码
     * 
     * @param user
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/password")
    public String editPassowrd(@ModelAttribute User user, Model model)
	    throws Exception {
	if (user == null || user.getId() == 0) {
	    return "/user/password";
	}
	if (!user.getNewPassword().equals(user.getPasswordrpt())) {
	    model.addAttribute("msg", "两次密码输入不一致。");
	    return "error";
	}
	User u = userService.authUser(user.getUserName(), MD5Util.md5(user
		.getPassword()));
	if (u == null) {
	    model.addAttribute("msg", "原密码错误。");
	    return "error";
	}
	user.setPassword(MD5Util.md5(user.getNewPassword()));
	userService.editUser(user);
	model.addAttribute("isEdit", true);
	return "user/success";
    }
}
